package com.empire.module.infra.service.location;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.empire.module.infra.dal.dataobject.location.LocationApiDO;
import com.empire.module.infra.dal.mysql.localtion.ApiLocationMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.List;
import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@Service
@Validated
public class ApiLocationHistoryServiceImpl implements ApiLocationHistoryService{

    @Resource
    private ApiLocationMapper apiLocationMapper;
    // 每批次删除数量（根据数据库性能调整，建议500-2000）
    private static final int BATCH_SIZE = 1000;

    @Override
    public void clean6YearHistoryLocation() {

        log.info("开始清理6个月前的定位数据...");

        // 计算6个月前的时间阈值（当前时间 - 6个月）
        LocalDateTime thresholdTime = LocalDateTime.now().minusMonths(6);
        log.info("清理阈值时间：{}", thresholdTime);

        int totalDeleted = 0;
        int batchDeleted;

        try {
            // 循环分批删除，直到本批次删除数量为0
            do {
                // 1. 查询本批次待删除的数据ID（仅查ID，减少内存占用）
                LambdaQueryWrapper<LocationApiDO> query = new LambdaQueryWrapper<>();
                query.lt(LocationApiDO::getLocationTime, thresholdTime)
                        .select(LocationApiDO::getId) // 只查询 id，减少内存占用
                        .last("LIMIT " + BATCH_SIZE);

                List<Object> idObjs = apiLocationMapper.selectObjs(query);
                if (idObjs.isEmpty()) {
                    batchDeleted = 0;
                    break;
                }

                // 2. 转换为 Long 类型列表
                List<Long> ids = idObjs.stream()
                        .map(obj -> Long.parseLong(obj.toString()))
                        .collect(Collectors.toList());


                if (ids.isEmpty()) {
                    break;
                }

                // 2. 批量删除本批次数据
                batchDeleted = apiLocationMapper.deleteByIds(ids);
                totalDeleted += batchDeleted;

                log.info("本次删除定位数据 {} 条，累计删除 {} 条", batchDeleted, totalDeleted);

                // 3. 每批删除后短暂休眠，减轻数据库压力（可选，根据性能调整）
                TimeUnit.MILLISECONDS.sleep(100);

            } while (batchDeleted == BATCH_SIZE); // 若本批次删满BATCH_SIZE，继续下一批

            log.info("6个月前定位数据清理完成，共删除 {} 条", totalDeleted);

        } catch (Exception e) {
            log.error("清理定位数据失败", e);
            throw new RuntimeException("清理定位数据异常", e); // 触发事务回滚
        }
    }
}
